<template>
  <div class="goods-container">
    <el-card>
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="handleAdd">新建商品</el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称"
          style="width: 200px; margin-left: 20px"
          @keyup.enter.native="searchGoods"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchGoods" />
        </el-input>
        <el-select 
          v-model="selectedCategory" 
          placeholder="选择分类" 
          clearable
          style="width: 150px; margin-left: 20px"
          @change="handleCategoryChange"
        >
          <el-option 
            v-for="item in categoryOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-table :data="goodsList" border v-loading="loading">
        <el-table-column label="商品图片" width="120">
          <template slot-scope="scope">
            <el-image 
              style="width: 80px; height: 80px"
              :src="scope.row.firstImageUrl"
              fit="cover"
              :preview-src-list="scope.row.firstImageUrl ? [scope.row.firstImageUrl] : []">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称" />
        <el-table-column prop="description" label="商品描述" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120" />
        
        <!-- 交易方式列 --> 
        <el-table-column label="交易方式" width="120"> 
          <template slot-scope="scope"> 
            <span v-if="scope.row.deliveryMethod === DeliveryMethod.FACE_TO_FACE">面交</span> 
            <span v-else-if="scope.row.deliveryMethod === DeliveryMethod.MAIL">邮寄</span> 
            <span v-else-if="scope.row.deliveryMethod === DeliveryMethod.BOTH">两者都可</span> 
            <span v-else>未设置</span> 
          </template> 
        </el-table-column> 
        
        <!-- 议价选项列 --> 
        <el-table-column label="议价选项" width="120"> 
          <template slot-scope="scope"> 
            <span v-if="scope.row.bargainOption === BargainOption.NO_BARGAIN">不议价</span> 
            <span v-else-if="scope.row.bargainOption === BargainOption.ALLOW_BARGAIN">允许砍价</span> 
            <span v-else-if="scope.row.bargainOption === BargainOption.NEGOTIABLE">可协商</span> 
            <span v-else>未设置</span> 
          </template> 
        </el-table-column>
        
        <el-table-column prop="price" label="价格" width="120">
          <template slot-scope="scope">
            ￥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    
    <!-- 商品编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="goodsForm" label-width="100px">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择商品分类" style="width: 100%">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        <!-- 交易方式选择 -->
        <el-form-item label="交易方式" prop="deliveryMethod">
          <el-select v-model="form.deliveryMethod" placeholder="请选择交易方式">
            <el-option
              v-for="item in deliveryMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 议价选项 -->
        <el-form-item label="议价选项" prop="bargainOption">
          <el-select v-model="form.bargainOption" placeholder="请选择议价选项">
            <el-option
              v-for="item in bargainOptionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 自动更新 -->
        <el-form-item label="自动更新" prop="autoRenew">
          <el-switch v-model="form.autoRenew"></el-switch>
        </el-form-item>
        <el-form-item label="商品位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入商品位置"></el-input>
        </el-form-item>
        <!-- 删除这两个多余的字段 -->
        <!-- <el-form-item label="是否更新" prop="isRenewal">
          <el-switch v-model="form.isRenewal"></el-switch>
        </el-form-item>
        <el-form-item label="是否特价" prop="isBargain">
          <el-switch v-model="form.isBargain"></el-switch>
        </el-form-item> -->
        <el-form-item label="商品图片" prop="imageUrls">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            multiple>
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">支持jpg、png格式，最多上传5张图片</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsList, saveGoods, getGoodsDetail } from '@/api/goods'
import { DeliveryMethod, BargainOption, deliveryMethodOptions, bargainOptionOptions, getDeliveryMethodFromOldFields, getBargainOptionFromOldFields } from '@/utils/enums'

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      goodsList: [],
      loading: false,
      searchKeyword: '',
      selectedCategory: '',
      categoryOptions: [
        { value: '电子产品', label: '电子产品' },
        { value: '家居', label: '家居' },
        { value: '服饰', label: '服饰' },
        { value: '图书', label: '图书' },
        { value: '运动', label: '运动' }
      ],
      // 添加以下缺失的变量定义
      dialogVisible: false,
      dialogTitle: '',
      form: { // 这里应该是form而不是data函数
        id: '',
        title: '',
        description: '',
        category: '',
        price: 0,
        deliveryMethod: DeliveryMethod.NONE, // 替换原来的tradingMethod
        bargainOption: BargainOption.NEGOTIABLE, // 替换原来的isBargain
        location: '',
        autoRenew: false, // 原isRenewal改为autoRenew
        imageUrls: []
      },
      rules: {
        title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        deliveryMethod: [{ required: true, message: '请选择交易方式', trigger: 'change' }],
        bargainOption: [{ required: true, message: '请选择议价选项', trigger: 'change' }],
        location: [{ required: true, message: '请输入商品位置', trigger: 'blur' }]
      },
      // 其他必要的数据
      DeliveryMethod,
      BargainOption,
      deliveryMethodOptions,
      bargainOptionOptions,
      fileList: [],
      submitting: false
    }
  },
  created() {
    this.fetchGoodsList()
  },
  methods: {
    // 添加formatDate函数
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      if (isNaN(date.getTime())) return dateString
      
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    
    async fetchGoodsList() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword || undefined,
          category: this.selectedCategory || undefined
        }
        
        const response = await getGoodsList(params)
        console.log('API返回数据:', response)
        
        if (response.success) {
          // 修改这里：从products获取数据而不是items
          this.goodsList = (response.data.products || []).map(item => {
            return {
              ...item,
              // 确保有新字段，如果没有则从旧字段推断
              deliveryMethod: item.deliveryMethod !== undefined ? item.deliveryMethod : getDeliveryMethodFromOldFields(item),
              bargainOption: item.bargainOption !== undefined ? item.bargainOption : getBargainOptionFromOldFields(item),
              autoRenew: item.autoRenew !== undefined ? item.autoRenew : (item.isRenewal || false)
            }
          })
          // 修改这里：从pagination.total获取总数
          this.total = response.data.pagination.total || 0
        } else {
          this.$message.error(response.message || '获取商品列表失败')
          this.goodsList = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败：' + (error.message || '未知错误'))
        this.goodsList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchGoodsList()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchGoodsList()
    },
    
    searchGoods() {
      this.currentPage = 1
      this.fetchGoodsList()
    },
    
    handleCategoryChange() {
      this.currentPage = 1
      this.fetchGoodsList()
    },
    
    handleAdd() {
      this.dialogTitle = '新建商品'
      this.form = {
        id: '',
        title: '',
        description: '',
        category: '',
        price: 0,
        tradingMethod: '',
        location: '',
        isRenewal: false,
        isBargain: false,
        imageUrls: []
      }
      this.fileList = []
      this.dialogVisible = true
    },
    
    handleEdit(row) {
      this.dialogTitle = '编辑商品';
      this.loading = true;
      
      // 先使用列表数据初始化表单
      this.form = {
        id: row.id || '',
        title: row.title || '',
        description: row.description || '',
        category: row.category || '',
        price: row.price || 0,
        // 使用新的枚举字段，同时兼容旧字段
        deliveryMethod: row.deliveryMethod !== undefined ? row.deliveryMethod : getDeliveryMethodFromOldFields(row),
        bargainOption: row.bargainOption !== undefined ? row.bargainOption : getBargainOptionFromOldFields(row),
        location: row.location || '',
        autoRenew: row.autoRenew !== undefined ? row.autoRenew : (row.isRenewal || false),
        imageUrls: row.imageUrls || []
      };
      
      // 处理图片列表
      this.fileList = (row.imageUrls || []).map((url, index) => ({
        name: `图片${index + 1}`,
        url: url
      }));
      
      this.dialogVisible = true;
      
      // 调用商品详情API获取完整数据
      getGoodsDetail(row.id)
        .then(response => {
          if (response.success && response.data) {
            const detail = response.data;
            console.log('商品详情数据:', detail);
            
            // 使用详情数据更新表单
            this.form = {
              id: detail.id,
              title: detail.title,
              description: detail.description,
              category: detail.category,
              price: detail.price,
              // 优先使用新字段，兼容旧字段
              deliveryMethod: detail.deliveryMethod !== undefined ? detail.deliveryMethod : getDeliveryMethodFromOldFields(detail),
              bargainOption: detail.bargainOption !== undefined ? detail.bargainOption : getBargainOptionFromOldFields(detail),
              location: detail.location,
              autoRenew: detail.autoRenew !== undefined ? detail.autoRenew : (detail.isRenewal || false),
              imageUrls: detail.imageUrls || []
            };
            
            // 更新图片列表
            this.fileList = (detail.imageUrls || []).map((url, index) => ({
              name: `图片${index + 1}`,
              url: url
            }));
          } else {
            console.warn('获取商品详情失败，使用列表数据');
          }
        })
        .catch(error => {
          console.error('获取商品详情失败:', error);
          this.$message.warning('获取商品详情失败，使用列表数据');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(0, 5) // 最多5张图片
    },
    
    handleFileRemove(file, fileList) {
      this.fileList = fileList
    },
    
    resetForm() {
      this.$refs.goodsForm && this.$refs.goodsForm.resetFields()
      this.fileList = []
      this.submitting = false
    },
    
    async submitForm() {
      this.$refs.goodsForm.validate(async valid => {
        if (!valid) return;
        
        this.submitting = true;
        
        try {
          // 处理图片上传
          const imageUrls = this.fileList.map(file => {
            return file.url || '图片URL';
          });
          
          // 构建提交数据，同时兼容新旧字段
          const formData = {
            id: this.form.id,
            title: this.form.title,
            description: this.form.description,
            category: this.form.category,
            price: parseFloat(this.form.price),
            // 新字段
            deliveryMethod: this.form.deliveryMethod,
            bargainOption: this.form.bargainOption,
            autoRenew: this.form.autoRenew,
            location: this.form.location, // 添加这一行
            // 兼容旧字段
            dealFace: this.form.deliveryMethod === DeliveryMethod.FACE_TO_FACE || this.form.deliveryMethod === DeliveryMethod.BOTH,
            dealMail: this.form.deliveryMethod === DeliveryMethod.MAIL || this.form.deliveryMethod === DeliveryMethod.BOTH,
            noBargain: this.form.bargainOption === BargainOption.NO_BARGAIN,
            allowBargain: this.form.bargainOption === BargainOption.ALLOW_BARGAIN,
            isRenewal: this.form.autoRenew,
            imageUrls: imageUrls
          };
          
          const response = await saveGoods(formData);
          
          if (response.success) {
            this.$message.success(this.form.id ? '更新成功' : '创建成功');
            this.dialogVisible = false;
            this.fetchGoodsList();
          } else {
            this.$message.error(response.message || '操作失败');
          }
        } catch (error) {
          console.error('保存商品失败:', error);
          this.$message.error('保存失败：' + (error.message || '未知错误'));
        } finally {
          this.submitting = false;
        }
      });
    }
  }
}
</script>

<style scoped>
.goods-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.el-upload__tip {
  line-height: 1.2;
  margin-top: 5px;
  color: #909399;
}
</style>
